package util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;

public class OssUtil {
	
	public static String ACCESS_ID = "LTAIpedBAmF1Qzxx";
	public static String ACCESS_KEY = "SpB8lXbRV2mFs0s5UtiRCSn6dAfP3c";
	public static String OSS_ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";
	
	public static String BUCKET_NAME = "";
	
	/**
	* 创建Bucket
	* @param client OSSClient对象
	* @param bucketName BUCKET名
	* @throws OSSException
	* @throws ClientException
	*/
	public static void ensureBucket()throws OSSException, ClientException{
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		try{
			client.createBucket(BUCKET_NAME);
			
		}catch(ServiceException e){
				if(!OSSErrorCode.BUCKET_ALREADY_EXISTS.equals(e.getErrorCode())){
					throw e;
				}
			}finally{
				client.shutdown();
			}
		}
	
	/**
	* 删除一个Bucket和其中的Objects
	* @param client OSSClient对象
	* @param bucketName Bucket名
	* @throws OSSException
	* @throws ClientException
	*/
	public static void deleteBucket()throws OSSException, ClientException{
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		ObjectListing ObjectListing = client.listObjects(BUCKET_NAME);
		List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
		for(int i = 0; i < listDeletes.size(); i++){
			String objectName = listDeletes.get(i).getKey();
			System.out.println("objectName = " + objectName);
			client.deleteObject(BUCKET_NAME, objectName);
		}
		client.deleteBucket(BUCKET_NAME);
		client.shutdown();
	}
	
	/**
	* 把Bucket设置成所有人可读
	* @param client OSSClient对象
	* @param bucketName Bucket名
	* @throws OSSException
	* @throws ClientException
	*/
	public static void setBucketPublicReadable()throws OSSException, ClientException{
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		client.createBucket(BUCKET_NAME);
		client.setBucketAcl(BUCKET_NAME, CannedAccessControlList.PublicRead);
		client.shutdown();
	}
	
	/**
	* 上传文件
	* @param client OSSClient对象
	* @param bucketName Bucket名
	* @param Objectkey 上传到OSS起的名
	* @param filename 本地文件名
	* @throws OSSException
	* @throws ClientException
	* @throws FileNotFoundException
	*/
	public static String uploadFile(MultipartFile multipartFile,String path)throws OSSException, ClientException, FileNotFoundException{
		if (multipartFile != null && multipartFile.getSize() != 0) {
			OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
			String org_name  = multipartFile.getOriginalFilename();
			String suffix = org_name.substring(org_name.lastIndexOf("."));
			if(suffix.equals(".tbi")){
				suffix = ".jpg";
			}
        	CommonsMultipartFile cf= (CommonsMultipartFile)multipartFile; 
        	DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
			File file = fi.getStoreLocation();
			String fileName = file.getName().substring(0,file.getName().indexOf(".tmp"))+suffix;
			ObjectMetadata objectMeta = new ObjectMetadata();
			objectMeta.setContentLength(file.length());
				if (fileName.endsWith("xml")) {
					objectMeta.setContentType("text/xml");
				}

				else if (fileName.endsWith("jpg")) {
					objectMeta.setContentType("image/jpeg");
				}

				else if (fileName.endsWith("png")) {
					objectMeta.setContentType("image/png");
				}
				
				InputStream input = new FileInputStream(file);
				String serverFileName = String.valueOf(new java.util.Date().getTime())+multipartFile.getSize()+suffix;
				client.putObject(BUCKET_NAME, path+serverFileName, input, objectMeta);
				
				//例如  http：//  或者 https://
				String start = OSS_ENDPOINT.substring(0, OSS_ENDPOINT.indexOf("://")+3);
				//例如  nanrinanritest.oss-cn-beijing.aliyuncs.com
				String mid = BUCKET_NAME+"."+OSS_ENDPOINT.substring(OSS_ENDPOINT.indexOf("://")+3)+"/";
				client.shutdown();
				return start + mid+ path+serverFileName;
		} else {
			return null;
		}	
	}
	
	public static String FileTempToUploadDeleteTemp(String fileA,String path)throws OSSException, ClientException, FileNotFoundException{
		
			
		/*	File file = new File(fileA);
			ObjectMetadata objectMeta = new ObjectMetadata();
			OSSObject abc = client.getObject(new GetObjectRequest(BUCKET_NAME, fileA.substring(fileA.indexOf(".com")+5)));
			InputStream input = abc.getObjectContent();
			client.putObject(BUCKET_NAME, path+file.getName(), input, objectMeta);
			client.deleteObject(BUCKET_NAME, fileA.substring(fileA.indexOf(".com")+5));
			
			String start = OSS_ENDPOINT.substring(0, OSS_ENDPOINT.indexOf("://")+3);
			//例如  nanrinanritest.oss-cn-beijing.aliyuncs.com
			String mid = BUCKET_NAME+"."+OSS_ENDPOINT.substring(OSS_ENDPOINT.indexOf("://")+3)+"/";*/
			String newFilePath = copyFile(fileA,path);
			OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
			client.deleteObject(BUCKET_NAME, fileA.substring(fileA.indexOf(".com")+5));
			client.shutdown();
			return newFilePath;
			
	}
	
	public static String FileUploadToTemp(String fileA,String path)throws OSSException, ClientException, FileNotFoundException{
		/*OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		File file = new File(fileA);
		ObjectMetadata objectMeta = new ObjectMetadata();
		OSSObject abc = client.getObject(new GetObjectRequest(BUCKET_NAME, fileA.substring(fileA.indexOf(".com")+5)));
		InputStream input = abc.getObjectContent();
		client.putObject(BUCKET_NAME, path+file.getName(), input, objectMeta);
		client.shutdown();
		String start = OSS_ENDPOINT.substring(0, OSS_ENDPOINT.indexOf("://")+3);
		//例如  nanrinanritest.oss-cn-beijing.aliyuncs.com
		String mid = BUCKET_NAME+"."+OSS_ENDPOINT.substring(OSS_ENDPOINT.indexOf("://")+3)+"/";*/
		return  copyFile(fileA,path);
	}
	/**
	* 下载文件
	* @param client OSSClient对象
	* @param bucketName Bucket名
	* @param Objectkey 上传到OSS起的名
	* @param filename 文件下载到本地保存的路径
	* @throws OSSException
	* @throws ClientException
	*/
	public static void downloadFile(String Objectkey, String filename)throws OSSException, ClientException {
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		client.getObject(new GetObjectRequest(BUCKET_NAME, Objectkey),new File(filename));
		client.shutdown();
	}	
	
	/**
	* 删除文件
	* @param fileName  全路径
	*/
	public static void  deleteFile(String fileName){
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		try {
			client.deleteObject(BUCKET_NAME,fileName.substring(fileName.indexOf(".com")+5));
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			client.shutdown();
		}
	}
	
	/**
	 * 批量上传时使用
	 * @param file
	 * @param path
	 * @return
	 * @throws OSSException
	 * @throws ClientException
	 * @throws FileNotFoundException
	 */
	public static String uploadBatchFile(File file,String path)throws OSSException, ClientException, FileNotFoundException{
		if (file != null && file.isFile() && file.exists()&&file.length() != 0) {
			OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
			String org_name  = file.getName();
			String suffix = org_name.substring(org_name.lastIndexOf("."));
			if(suffix.equals(".tbi")){
				suffix = ".jpg";
			}
			String fileName = file.getName().substring(0,file.getName().lastIndexOf("."))+suffix;
			ObjectMetadata objectMeta = new ObjectMetadata();
			objectMeta.setContentLength(file.length());
				if (fileName.endsWith("xml")) {
					objectMeta.setContentType("text/xml");
				}

				else if (fileName.endsWith("jpg")) {
					objectMeta.setContentType("image/jpeg");
				}

				else if (fileName.endsWith("png")) {
					objectMeta.setContentType("image/png");
				}
				
				InputStream input = new FileInputStream(file);
				String serverFileName = String.valueOf(new java.util.Date().getTime())+file.length()+suffix;
				client.putObject(BUCKET_NAME, path+serverFileName, input, objectMeta);
				
				//例如  http：//  或者 https://
				String start = OSS_ENDPOINT.substring(0, OSS_ENDPOINT.indexOf("://")+3);
				//例如  nanrinanritest.oss-cn-beijing.aliyuncs.com
				String mid = BUCKET_NAME+"."+OSS_ENDPOINT.substring(OSS_ENDPOINT.indexOf("://")+3)+"/";
				client.shutdown();
				return start + mid+ path+serverFileName;
		} else {
			return null;
		}	
	}

	public static String copyFile(String filepath,String destSrc){
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		try{
			String suffix = filepath.substring(filepath.lastIndexOf("."));
			String org_file_name = filepath.substring(filepath.lastIndexOf("/")+1,filepath.length());
			String serverFileName = String.valueOf(new java.util.Date().getTime())+StringUtil.getRandomString(10)+suffix;
			String bucketFilePath = filepath.substring(filepath.indexOf(".com")+5);
			// 创建CopyObjectRequest对象
			CopyObjectRequest copyObjectRequest = new CopyObjectRequest(BUCKET_NAME, bucketFilePath, BUCKET_NAME, destSrc + org_file_name);
			// 设置新的Metadata
			ObjectMetadata meta = new ObjectMetadata();
			
			if (filepath.endsWith("xml")) {
				meta.setContentType("text/xml");
			}

			else if (filepath.endsWith("jpg")) {
				meta.setContentType("image/jpeg");
			}

			else if (filepath.endsWith("png")) {
				meta.setContentType("image/png");
			}
			copyObjectRequest.setNewObjectMetadata(meta);
			// 复制Object
			CopyObjectResult result = client.copyObject(copyObjectRequest);
			String start = OSS_ENDPOINT.substring(0, OSS_ENDPOINT.indexOf("://")+3);
			//例如  nanrinanritest.oss-cn-beijing.aliyuncs.com
			String mid = BUCKET_NAME+"."+OSS_ENDPOINT.substring(OSS_ENDPOINT.indexOf("://")+3)+"/"; 
			return start + mid+destSrc + org_file_name;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			client.shutdown();
		}
		return "";
	}
	public static boolean testIF(String path){
	    OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
	    boolean found = client.doesObjectExist(BUCKET_NAME, path);
	    client.shutdown();
	    return found;
	  }
	
	public static String copyFileFullPath(String filepath,String destSrc){
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		String bucketFilePath = filepath.substring(filepath.indexOf(".com")+5);
		destSrc = destSrc.substring(filepath.indexOf(".com")+5);
		// 创建CopyObjectRequest对象
		CopyObjectRequest copyObjectRequest = new CopyObjectRequest(BUCKET_NAME, bucketFilePath, BUCKET_NAME, destSrc);
		// 设置新的Metadata
		ObjectMetadata meta = new ObjectMetadata();
		
		if (destSrc.endsWith("xml")) {
			meta.setContentType("text/xml");
		}

		else if (destSrc.endsWith("jpg")) {
			meta.setContentType("image/jpeg");
		}

		else if (destSrc.endsWith("png")) {
			meta.setContentType("image/png");
		}
		copyObjectRequest.setNewObjectMetadata(meta);
		// 复制Object
		CopyObjectResult result = client.copyObject(copyObjectRequest);
		client.shutdown();
		return destSrc;
	}
	
	public static String imgProcess(String key, String style){
		OSSClient ossClient = new OSSClient(OSS_ENDPOINT,ACCESS_ID, ACCESS_KEY);
	   
	    GetObjectRequest request = new GetObjectRequest(BUCKET_NAME, key);
	    request.setProcess(style);
	    String path = "d://"+new Date().getTime()+StringUtil.getRandomString(32)+".jpg";
	    ossClient.getObject(request, new File(path));
	    ossClient.shutdown();
	    return path;
	}
	public static String UploadQRImg(String path,byte[] file_bytes){
		OSSClient ossClient = new OSSClient(OSS_ENDPOINT,ACCESS_ID, ACCESS_KEY);
		// 上传字符串
		String fileName = path+"/"+String.valueOf(new java.util.Date().getTime()+"_QRcode.jpg");
		ossClient.putObject(BUCKET_NAME, fileName , new ByteArrayInputStream(file_bytes));
		String start = OSS_ENDPOINT.substring(0, OSS_ENDPOINT.indexOf("://")+3);
		String mid = BUCKET_NAME+"."+OSS_ENDPOINT.substring(OSS_ENDPOINT.indexOf("://")+3)+"/";
		// 关闭client
		ossClient.shutdown();
		return start+mid+fileName;
	}
	public static void main(String[] args) {
		/*String fileA ="http://ym-uniplaza.oss-cn-beijing.aliyuncs.com/Upload/good/875/1504766768637509084.png";
		String path  = "nanriTest/Test/";
		String b = copyFile(fileA,path);
		System.out.println(b);*/
		//http://ym-uniplaza.oss-cn-beijing.aliyuncs.com/Upload/good/987/standard/1512098640398175966.jpg
		String fileA ="http://ym-uniplaza.oss-cn-beijing.aliyuncs.com/Upload/good/987/standard/1512098640398175966.jpg";
		String path  = "nanriTest/Test/";
		nanriTestCopy(fileA,path);
		
	}
	public static String nanriTestCopy(String filepath,String destSrc){
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
		String suffix = filepath.substring(filepath.lastIndexOf("."));
		String org_file_name = filepath.substring(filepath.lastIndexOf("/")+1,filepath.length());
		String serverFileName = String.valueOf(new java.util.Date().getTime())+StringUtil.getRandomString(10)+suffix;
		String bucketFilePath = filepath.substring(filepath.indexOf(".com")+5);
		
		boolean found = client.doesObjectExist(BUCKET_NAME, bucketFilePath);
		if(found){
			// 创建CopyObjectRequest对象
			CopyObjectRequest copyObjectRequest = new CopyObjectRequest(BUCKET_NAME, bucketFilePath, BUCKET_NAME, destSrc + org_file_name);
			// 设置新的Metadata
		//	boolean found = ossClient.doesObjectExist(BUCKET_NAME, "<key>")
			ObjectMetadata meta = new ObjectMetadata();
			
			if (filepath.endsWith("xml")) {
				meta.setContentType("text/xml");
			}

			else if (filepath.endsWith("jpg")) {
				meta.setContentType("image/jpeg");
			}

			else if (filepath.endsWith("png")) {
				meta.setContentType("image/png");
			}
			copyObjectRequest.setNewObjectMetadata(meta);
			// 复制Object
			CopyObjectResult result = client.copyObject(copyObjectRequest);
			String start = OSS_ENDPOINT.substring(0, OSS_ENDPOINT.indexOf("://")+3);
			//例如  nanrinanritest.oss-cn-beijing.aliyuncs.com
			String mid = BUCKET_NAME+"."+OSS_ENDPOINT.substring(OSS_ENDPOINT.indexOf("://")+3)+"/";	
			client.shutdown();
			return start + mid+destSrc + org_file_name;
		}else{
			client.shutdown();
			return "";
		}
		
		
	}
}
